package itypes

import (
	"server/game/model"

	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/updater"
)

var History = history{}

//func init() {
//	History.IType = *NewIType(config.ITypeHistory)
//	if err := updater.Register(updater.ParserTypeCollection, updater.RAMTypeAlways, &model.History{}, &History); err != nil {
//		logger.Panic(err)
//	}
//}

type history struct {
	IType
}

func (this *history) Count(u *updater.Updater, key int32, start, end *times.Times) (r int64, err error) {
	val, err := this.Multiple(u, []int32{key}, start, end)
	if err != nil {
		return 0, err
	}
	return val[key], nil
}

// Multiple 统计一段时间内的日常总和
// todo 大于缓存周期的直接使用数据库
func (this *history) Multiple(u *updater.Updater, keys []int32, start, end *times.Times) (r map[int32]int64, err error) {
	if len(keys) == 0 {
		return nil, values.Errorf(0, "keys empty")
	}
	var rows []*model.Daily
	tx := model.DB().Where("uid = ?", u.Uid()).Select("value")
	if start != nil {
		s, _ := start.Sign(0)
		tx = tx.Where("iid >= ?", s)
	}
	if end != nil {
		s, _ := end.Sign(0)
		tx = tx.Where("iid <= ?", s)
	}

	if tx = tx.Find(&rows); tx.Error != nil {
		return nil, tx.Error
	}
	r = map[int32]int64{}
	for _, row := range rows {
		if row.Value != nil {
			for _, k := range keys {
				r[k] += row.Value[k]
			}
		}
	}
	return
}

// Weekly 周统计  offset=0当前周, -1:上周
func (this *history) Weekly(u *updater.Updater, keys []int32, offset int) (r map[int32]int64, err error) {
	star := times.Weekly(offset)
	end, _ := star.Expire(times.ExpireTypeWeekly, 1)
	return this.Multiple(u, keys, star, end)
}

// Monthly 月统计统计 同周,但是每月天数不一样,按自然月算
func (this *history) Monthly(u *updater.Updater, keys []int32, offset int) (r map[int32]int64, err error) {
	star := times.Monthly(offset)
	end, _ := star.Expire(times.ExpireTypeMonthly, 1)
	return this.Multiple(u, keys, star, end)
}
